package apy.codecase.business.view.activity;

import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;

import java.util.List;

import apy.codecase.R;
import apy.codecase.base.BaseActivity;
import apy.codecase.greendao.AppDaoUtils;
import apy.codecase.model.AppDaoModel;
import apy.codecase.utils.AToast;
import apy.codecase.utils.Md5Utils;
import apy.codecase.utils.UIUtils;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/10/24.
 * 注册
 */

public class RegisterActivity extends BaseActivity {

    @BindView(R.id.register_confirm)
    Button registerConfirm;
    @BindView(R.id.register_psw)
    EditText registerPsw;
    @BindView(R.id.register_confirm_psw)
    EditText registerConfirmPsw;
    @BindView(R.id.register_account)
    EditText registerAccount;

    @OnClick(R.id.register_confirm)
    public void onViewClicked() {
        String registerPsw = this.registerPsw.getText().toString().trim();
        String registerConfirmPsw = this.registerConfirmPsw.getText().toString().trim();
        String account = registerAccount.getText().toString().trim();
        if(TextUtils.isEmpty(account)){
            AToast.showTextToast("账号不能为空");
            return;
        }
        if (account.length() < 6 || account.length() > 18) {
            AToast.showTextToast("账号不能小于六位或者大于18位");
            return;
        }
        if (registerPsw.length() < 6 || registerConfirmPsw.length() > 18) {
            AToast.showTextToast("密码不能小于六位或者大于18位");
            return;
        }

        if (!registerPsw.equals(registerConfirmPsw)) {
            AToast.showTextToast("两次密码不一致");
            return;
        }

        long l = System.currentTimeMillis();
        String ticket = Md5Utils.encode(account + registerConfirmPsw) + String.valueOf(l);

        AppDaoUtils appDaoUtils = new AppDaoUtils(this);
        List<AppDaoModel> appDaoModels = appDaoUtils.queryAppDaoModelByQueryBuilder2(account);
        for (AppDaoModel model:appDaoModels) {
            if(model.getAccount().equals(account)){
                AToast.showTextToast("账户已存在");
                return;
            }
        }

        AppDaoModel model = new AppDaoModel();
        model.setTicket(ticket);
        model.setAppPsw(registerPsw);
        model.setAccount(account);
        model.setId(UIUtils.loadCurrentDateMillis()+account);
        boolean state = appDaoUtils.insertAppDaoModel(model);
        if(state){
            AToast.showTextToast("密码设置成功");
            finish();
        }
    }

    @Override
    protected String title() {
        return null;
    }

    @Override
    protected boolean controlTitle() {
        return false;
    }

    @Override
    protected int getViewId() {
        return R.layout.activity_register;
    }

    @Override
    protected void initData() {

    }
}
